package entry;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

@WebServlet("/pic/*")
public class ShowPic extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //这个地方会拿到对应图片的地址，要先获取流然后返回回去，写吧，，累死了，，
        String uri=req.getRequestURI();
        String name=uri.substring(uri.lastIndexOf("/")+1);
        File[] files=new File(String.valueOf(getServletContext().getAttribute("picPath"))).listFiles();
        for (File file : files) {
            if (file.getName().equals(name)){
                //在这里找到了对应匹配的文件
                ServletOutputStream servletOutputStream= resp.getOutputStream();
                resp.setContentType("image/jpeg");
                InputStream inputStream=new FileInputStream(file);
                byte[] bytes=new byte[1024];
                int bufLen=0;
                while ((bufLen=inputStream.read(bytes))!=-1){
                    servletOutputStream.write(bytes,0,bufLen);
                }

                inputStream.close();
                servletOutputStream.close();
                return;
            }
        }


    }
}
